package com.coda.service.impl;

import com.alibaba.druid.sql.visitor.functions.If;
import com.alibaba.fastjson.JSON;
import com.coda.Constant.MessageConstant;
import com.coda.Constant.StatusConstant;
import com.coda.common.PageResult;
import com.coda.common.Result;
import com.coda.context.BaseContext;
import com.coda.dto.PageDto;
import com.coda.entity.Auth;
import com.coda.entity.Role;
import com.coda.entity.User;
import com.coda.exception.BaseException;
import com.coda.mapper.RoleMapper;
import com.coda.mapper.UserMapper;
import com.coda.service.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.lettuce.core.output.ListSubscriber;
import org.apache.ibatis.annotations.ResultType;
import org.omg.CORBA.INTERNAL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import sun.security.krb5.internal.rcache.AuthList;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;


    /**
     * 获取当前登录的用户信息
     *
     * @return
     */
    // todo 将user转换为currentUser返回
    @Override
    public User getUserInfo() {

        //根据线程中的id获取当前用户的id
        User user = userMapper.getUserById(BaseContext.getCurrentId());
        return user;
    }



    /**
     * 分页查询用户信息
     *
     * @param pageDto
     * @param user
     * @return
     */
    @Override
    public PageResult getUserList(PageDto pageDto, User user) {
        //设置分页参数
        PageHelper.startPage(pageDto.getPageNum(), pageDto.getPageSize());
        //分页查寻
        Page<User> userList = userMapper.getUserList(user);

        PageResult pageResult = new PageResult(userList.getTotal(), userList.getResult());

        return pageResult;
    }

    /**
     * 添加用户
     *
     * @param user
     */
    @Override
    public void addUser(User user) {
        //判断用户是否存在
        User userInfo = userMapper.getUserByName(user.getUserCode());
        if (userInfo != null) {
            throw new BaseException(Result.CODE_ERR_BUSINESS, MessageConstant.USER_EXIST);
        }

        //设置默认状态为启动
        user.setUserState(StatusConstant.USER_STATE_PASS);
        //将密码md5加密
        user.setUserPwd(DigestUtils.md5DigestAsHex(user.getUserPwd().getBytes()));
        userMapper.addUser(user);
    }

    /**
     * 修改用户状态
     *
     * @param user
     */
    // todo 如果当前用户级别低于要更新的用户则不能修改状态
    @Override
    public void updateState(User user) {
        //获取当前用户的类型
        User userInfo = userMapper.getUserById(BaseContext.getCurrentId());
        //获取请求中用户的类型
        User responseUser = userMapper.getUserById(user.getUserId());

        //如果当前用户级别低于要更新的用户则不能修改
//        if (userInfo.getUserType()>responseUser.getUserType()){
//            throw new BaseException(Result.CODE_ERR_BUSINESS,MessageConstant.NOT_AUTH);
//        }
        userMapper.update(user);
    }

    /**
     * 根据id删除单个用户
     *
     * @param id
     */
    @Override
    @Transactional
    public void deleteUserById(Long id) {

        //获取当前用户
        User userInfo = userMapper.getUserById(BaseContext.getCurrentId());
        //获取请求中要删除的用户
        User userById = userMapper.getUserById(id);
        //当删除比自己级别更高的用户时，不能删除
        if (Integer.parseInt(userInfo.getUserType()) > Integer.parseInt(userById.getUserType())) {
            throw new BaseException(Result.CODE_ERR_BUSINESS, MessageConstant.NOT_DELETE_USER);
        }

        //如果用户为启用状态不能删除
        if (userById.getUserState().equals(StatusConstant.USER_STATE_PASS)) {
            throw new BaseException(Result.CODE_ERR_BUSINESS, MessageConstant.STOP_ROLE);
        }

        //设置对象属性
        User user = new User();
        user.setIsDelete(StatusConstant.USER_STATE_PASS);
        user.setUserId(id);

        //删除用户
        userMapper.setStateUserById(user);
        //删除用户对应的角色
        roleMapper.deleteUserRoleByUserId(id);

    }

    /**
     * 批量删除用户
     *
     * @param ids
     */
    @Override
    public void deleteUserList(List<Long> ids) {

        //获取当前用户
        User userInfo = userMapper.getUserById(BaseContext.getCurrentId());

        //遍历需要删除的用户id
        for (Long id : ids) {
            //获取请求中要删除的用户
            User user = userMapper.getUserById(id);

            //当删除比自己级别更高的用户时，不能删除
            if (Integer.parseInt(userInfo.getUserType()) > Integer.parseInt(user.getUserType())) {
                throw new BaseException(Result.CODE_ERR_BUSINESS, MessageConstant.NOT_DELETE_USER);
            }

            //如果用户为启用状态不能删除
            if (user.getUserState().equals(StatusConstant.USER_STATE_PASS)) {
                throw new BaseException(Result.CODE_ERR_BUSINESS, MessageConstant.STOP_ROLE);
            }
        }
        //批量删除用户
        userMapper.setstateUserList(ids);
        //批量删除用户对应的角色
        roleMapper.deleteUserRoleLIst(ids);
    }

    /**
     * 根据id修改用户信息
     *
     * @param user
     */
    @Override
    public void updateUser(User user) {

        //获取当前用户
        User userInfo = userMapper.getUserById(BaseContext.getCurrentId());
        //获取请求中的用户
        User userById = userMapper.getUserById(user.getUserId());
        //当修改比自己级别更高的用户时，不能修改
        if (Integer.parseInt(userInfo.getUserType()) > Integer.parseInt(userById.getUserType())) {
            throw new BaseException(Result.CODE_ERR_BUSINESS, MessageConstant.NOT_AUTH);
        }
        userMapper.update(user);
    }

    /**
     * 根据id重置密码
     *
     * @param id
     */
    @Override
    public void updatePwd(Long id) {

        //获取当前用户
        User userInfo = userMapper.getUserById(BaseContext.getCurrentId());
        //当修改比自己级别更高的用户时，不能修改
        if (!(userInfo.getUserType().equals("1"))) {
            throw new BaseException(Result.CODE_ERR_BUSINESS, MessageConstant.NOT_NOW_PASSWORD);
        }

        //md5加密重置密码
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        //存储数据库
        User user = new User();
        user.setUserPwd(password);
        user.setUserId(id);

        userMapper.updatePwd(user);
    }



}
